#include "SerializaReadWrite.h"
#include "SessionInit.h"
#include "TCPServer.h"
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <cassert>
#include <memory>
#include <queue>
#include <thread>
#include <unordered_map>

using namespace UTILS;

boost::asio::awaitable<void> TCPServer::accept() {
  try {
    while (!m_isStop_) {
      SerializaReadWritePtr sockptr =
          std::make_shared<SerializaReadWrite>(m_acceptor_.get_executor());
      boost::asio::ip::tcp::endpoint endpoint;
      boost::system::error_code ec;
      co_await m_acceptor_.async_accept(
          sockptr->socket(), endpoint,
          boost::asio::redirect_error(boost::asio::use_awaitable, ec));
      if (!ec) {
        auto ptr = std::make_shared<SessionInit>(sockptr);
        ptr->start();
      }
    }
  } catch (std::exception &e) {
    // 处理异常
  }
}

TCPServer::TCPServer(boost::asio::io_context &io, const tcp::endpoint &ep)
    : m_acceptor_(io, ep), m_isStop_{false},
      m_workGuard_(boost::asio::make_work_guard(m_acceptor_.get_executor())) {
  m_acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
}

void TCPServer::start() {
  m_isStop_ = false;
  auto self(shared_from_this());
  boost::asio::co_spawn(
      m_acceptor_.get_executor(), [self] { return self->accept(); },
      boost::asio::detached);
}

void TCPServer::stop() {
  if (m_acceptor_.is_open()) {
    m_acceptor_.cancel();
    // m_acceptor_.close();
  }
  m_isStop_ = true;
}

TCPServer::~TCPServer() {
  if (m_acceptor_.is_open()) {
    m_acceptor_.cancel();
    m_acceptor_.close();
  }
  m_workGuard_.reset(); // 明确释放work_guard
}